<?php

/**
 * ===============
 * innoTweets Auth
 * ===============
 * 
 * @author  Dino (DBK)
 * @date    1 Jan 2014
 */
class innoTweetsAuth {

  protected $apiUrl = 'http://localhost/innotweets/';
  protected $appToken = NULL;
  protected $callBack = NULL;
  protected $userToken = NULL;
  protected $response = array('status' => 0, 'msg' => '');

  public function appSettings($appToken = NULL, $callBack = NULL) {
    if (!empty($appToken) && !empty($callBack)) {
      $this->appToken = (string) $appToken;
      $this->callBack = (string) $callBack;
      return $this;
    } else {
      die('innoTweets API - App token or callback url missing.');
    }
  }

  private function getAuthToken() {
    $reqData = array();
    $reqData['app_token'] = $this->appToken;
    $reqData['app_callback'] = $this->callBack;
    return $this->url_get_contents($this->apiUrl . 'api/get_token?req_token=' . base64_encode(json_encode($reqData)));
  }

  public function getUserToken() {
    if (empty($this->userToken)) {
      if (isset($_GET['innotweets_user_token']) && !empty($_GET['innotweets_user_token'])) {
        return $this->userToken = (string) $_GET['innotweets_user_token'];
      } else {
        header('LOCATION: ' . $this->apiUrl . 'api/get_auth?api_token=' . $this->getAuthToken());
        return;
      }
    }
  }

  public function userToken($userToken = NULL) {
    $this->userToken = $userToken;
    return $this;
  }

  public function getUser() {
    if ($this->getUserToken()) {
      return json_decode($this->url_get_contents($this->apiUrl . "api/get_data?user_token=" . $this->userToken), TRUE);
    }
  }

  private function url_get_contents($Url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
  }

}
